<script setup lang="tsx">
import { provide, ref } from "vue";
import { Button, ClButton, ClGrid, Grid, GridUtils } from "@chulei-ui/components";
import { Container } from "typedi";
import { useDebounceFn } from "@vueuse/core";
import { ContractAvailabilityTexts, ContractStatusTexts, ContractTypeTexts } from "../../enum";
import { NumberUtils } from "../../utils/NumberUtils";
import { ContractService } from "../../repositories/ContractService";
import ContractItems from "./ContractItems.vue";
import type { GridInstance, PageFetchParams } from "@chulei-ui/components";
import type { Contract } from "../../repositories/contracts/entity";
import { useContract } from "~pages/contracts/use-contract";
import { AuthRoleSelect } from "~pages/select";
import { ContractSettlementButton } from "~pages/contracts/column-actions";
import { ContractGridInstance } from "~pages/contracts/tokens";

const contractService = Container.get(ContractService);

const { calcTotalPrice } = useContract();

const gridOptions = ref<Grid.Options>({
  //@ts-ignore
  getRowId(row) {
    return row.data.contract_id;
  },
  rowClassRules: {
    "contract-finish": ({ data }: { data: Contract }) => data.status.startsWith("finished"),
    "contract-progress": ({ data }: { data: Contract }) =>
      data.status === "in_progress" || data.status === "outstanding",
    "contract-fail": ({ data }: { data: Contract }) =>
      data.status === "failed" || data.status === "deleted" || data.status === "cancelled",
  },
});

const columns = ref<Grid.Column<Contract & { estimatePrice: number; jitaBuyPrice: number }>[]>([
  {
    field: "contract_id",
    headerName: "合同编号",
    tooltipComponent: null,
    ...Grid.cellRender<Contract>(({ data }) => {
      const slots = {
        default: () => {
          return <el-link type="primary">{data!.contract_id}</el-link>;
        },
        content: () => {
          return <ContractItems items={data!.items} />;
        },
      };
      return <el-tooltip trigger="click" raw-content effect="light" v-slots={slots}></el-tooltip>;
    }),
    ...GridUtils.ValueGetter<Contract>(({ data }) => {
      return data!.contract_id;
    }),
  },
  {
    field: "title",
    headerName: "标题",
    minWidth: 250,
    valueFormatter({ data }) {
      if (data && !data.title) {
        return `${data.issuer_name} -> ${data.acceptor_name ?? "未指定"} (${ContractStatusTexts[data.status]})`;
      }
      return "";
    },
  },
  {
    field: "price",
    headerName: "合同价格",
    valueFormatter({ value }) {
      return NumberUtils.readableText(value);
    },
  },
  {
    field: "estimatePrice",
    headerName: "估价",
    valueGetter({ data }) {
      return calcTotalPrice(data!, (price) => price.estimate_price);
    },
    valueFormatter({ value }) {
      return NumberUtils.readableText(value);
    },
  },
  {
    field: "jitaBuyPrice",
    headerName: "吉他收单价",
    valueGetter({ data }) {
      return calcTotalPrice(data!, (price) => price.jita_avg_price);
    },
    valueFormatter({ value }) {
      return NumberUtils.readableText(value);
    },
  },
  {
    field: "settlement_estimate_price",
    headerName: "结算时的估价",
    valueFormatter({ value }) {
      return NumberUtils.readableText(value);
    },
  },
  {
    field: "settlement_jita_price",
    headerName: "结算时的吉他价格",
    valueFormatter({ value }) {
      return NumberUtils.readableText(value);
    },
  },
  {
    field: "settlement_discount",
    headerName: "结算折扣",
    valueFormatter({ value }) {
      if (value) {
        return `${value}`;
      }
      return "";
    },
  },
  {
    field: "settlement_price",
    headerName: "结算金额",
    valueFormatter({ value }) {
      return NumberUtils.readableText(value);
    },
  },
  {
    field: "date_issued",
    headerName: "创立日期",
  },
  {
    field: "date_completed",
    headerName: "完成日期",
  },
  {
    field: "issuer_name",
    headerName: "发布人",
  },
  {
    field: "acceptor_name",
    headerName: "接收",
  },
  {
    field: "volume",
    headerName: "体积",
    valueFormatter({ data }) {
      return NumberUtils.readableText(data!.volume!);
    },
  },
  {
    field: "availability",
    headerName: "访问性",
    valueFormatter({ data }) {
      return ContractAvailabilityTexts[data!.availability];
    },
  },
  {
    field: "type",
    headerName: "类型",
    valueFormatter({ data }) {
      return ContractTypeTexts[data!.type];
    },
  },
  {
    field: "status",
    headerName: "状态",
    valueFormatter({ data }) {
      return ContractStatusTexts[data!.status];
    },
  },
  {
    field: "end_location_id",
    pinned: "right",
    headerName: "操作",
    ...Grid.alwaysCellRender<Contract>(({ data }) => {
      return (
        <el-space>
          <ContractSettlementButton contract={data!} />
        </el-space>
      );
    }),
  },
]);

const fetch = async (page: PageFetchParams) => {
  return contractService.getContracts(playerId.value!, page);
};

const playerId = ref<number>();
const gridRef = ref<GridInstance>();
provide(ContractGridInstance, gridRef);

const syncEsiContracts = async () => {
  await contractService.syncContract(playerId.value!);
  await gridRef.value!.refresh();
};

const changePlayerContracts = useDebounceFn(async () => {
  await gridRef.value!.refresh();
}, 20);

defineOptions({
  name: "ContractTable",
});
</script>

<template>
  <div class="auth-role-table">
    <span class="flex mb-0.5">
      <AuthRoleSelect v-model="playerId" @change="changePlayerContracts" />
      <cl-button :disabled="!playerId" :type="Button.Type.primary" @click="syncEsiContracts">同步ESI合同</cl-button>
    </span>
    <div v-if="playerId" class="records">
      <cl-grid ref="gridRef" :grid-options="gridOptions" :columns="columns" :row-data="fetch" :page-size="1000" />
    </div>
  </div>
</template>

<style lang="scss">
.contract {
  &-finish {
    background-color: var(--el-color-success-light-7);
  }
  &-progress {
    background-color: var(--el-color-primary-light-7);
  }
  &-fail {
    background-color: var(--el-color-danger-light-7);
  }
}
.auth-role-table {
  height: 100%;
  display: flex;
  flex-direction: column;

  .records {
    flex: 1;
  }
}
</style>
